package com.application.chiettinhdienluc.adapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.Filter;
import android.widget.TextView;

import com.application.chiettinhdienluc.R;
import com.application.chiettinhdienluc.model.VattuModel;
import com.application.chiettinhdienluc.utils.Utils;

public class DanhMucVatTuAdapter extends BaseAdapter {
	public ArrayList<VattuModel> itemList;
	Animation animation = null;
	private List<VattuModel> vattuListShowing;
	private CharSequence currentFilter;

	public ArrayList<VattuModel> getItemList() {
		return itemList;
	}

	private Activity ac;
	private boolean isSelectVattu = false;

	public DanhMucVatTuAdapter(Activity context, ArrayList<VattuModel> itemList) {
		this.itemList = new ArrayList<VattuModel>(itemList);
		vattuListShowing = new ArrayList<VattuModel>(itemList);
		ac = context;
	}

	private class ViewHolder {
		TextView tv_ten_vat_tu;
		TextView tvStt;
		CheckBox name;
		TextView tv_quy_cach;
		TextView tv_don_gia;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final ViewHolder holder;
		// View view = null;
		if (convertView == null) {
			holder = new ViewHolder();
			LayoutInflater inflater = LayoutInflater.from(ac);
			convertView = inflater.inflate(R.layout.danh_muc_vat_tu_item, null);
			holder.name = (CheckBox) convertView.findViewById(R.id.cb);
			holder.tv_ten_vat_tu = (TextView) convertView.findViewById(R.id.tv_ten_vat_tu);
			holder.tvStt = (TextView) convertView.findViewById(R.id.tvStt);
			holder.tv_quy_cach = (TextView) convertView.findViewById(R.id.tv_quy_cach);
			holder.tv_don_gia = (TextView) convertView.findViewById(R.id.tv_don_gia);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		try {
			holder.name.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					CheckBox cb = (CheckBox) v;
					VattuModel item = (VattuModel) cb.getTag();
					Log.v("HAI", "Clicked on Checkbox: " + cb.getText() + " is " + cb.isChecked());
					item.setSuDung(cb.isChecked());
				}
			});
			animation = AnimationUtils.loadAnimation(ac, R.anim.push_up_in);
			convertView.startAnimation(animation);
			animation = null;
			holder.tvStt.setText(position + 1 + " .");

			VattuModel vattu = (VattuModel)getItem(position);
			holder.name.setChecked(vattu.isSuDung());
			// holder.tvMaVattuValue.setText(vattu.getMaVattu());
			holder.tv_ten_vat_tu.setText(vattu.getTenVattu());
			holder.tv_quy_cach.setText(vattu.getQuyCach());
			holder.tv_don_gia.setText(Utils.formatDoubleNumber(vattu.getDonGia())+ " " + ac.getString(R.string.str_dong));
			holder.name.setTag(vattu);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return convertView;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return vattuListShowing.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return vattuListShowing.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	public void setItemList(ArrayList<VattuModel> itemList) {
		this.itemList = new ArrayList<VattuModel>(itemList);
		vattuListShowing = new ArrayList<VattuModel>(itemList);
	}
	
	@Override
	public void notifyDataSetChanged() {
		if (currentFilter!=null) getFilter().filter(currentFilter);
		else vattuListShowing = new ArrayList<VattuModel>(itemList);
		super.notifyDataSetChanged();
	}
	
	/**
     * Lock used to modify the content of {@link #friendList}. Any write operation
     * performed on the array should be synchronized on this lock. This lock is also
     * used by the filter (see {@link #getFilter()} to make a synchronized copy of
     * the original array of data.
     */
    private final Object mLock = new Object();
    
    private ArrayFilter mFilter;

    /**
     * Sorts the content of this adapter using the specified comparator.
     *
     * @param comparator The comparator used to sort the objects contained
     *        in this adapter.
     */
//    public void sort(Comparator<? super VattuModel> comparator) {
//        synchronized (mLock) {
//            if (vattuListShowing != null) {
//                Collections.sort(vattuListShowing, comparator);
//            } else {
//                Collections.sort(itemList, comparator);
//            }
//        }
//        notifyDataSetChanged();
//    }

    /**
     * {@inheritDoc}
     */
    public Filter getFilter() {
        if (mFilter == null) {
            mFilter = new ArrayFilter();
        }
        return mFilter;
    }

	/**
     * <p>An array filter constrains the content of the array adapter with
     * a prefix. Each item that does not start with the supplied prefix
     * is removed from the list.</p>
     */
	private class ArrayFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence prefix) {
            FilterResults results = new FilterResults();
            if (vattuListShowing == null) {
                synchronized (mLock) {
                	vattuListShowing = new ArrayList<VattuModel>(itemList);
                }
            }

            if (prefix == null || prefix.length() == 0) {
                ArrayList<VattuModel> list;
                synchronized (mLock) {
                    list = new ArrayList<VattuModel>(itemList);
                }
                results.values = list;
                results.count = list.size();
            } else {
                String prefixString = prefix.toString().toLowerCase(Locale.getDefault());
                String filterText = Utils.convertSignToNoSign(prefixString);
                ArrayList<VattuModel> values;
                synchronized (mLock) {
                    values = new ArrayList<VattuModel>(itemList);
                }

                final int count = values.size();
                final ArrayList<VattuModel> newValues = new ArrayList<VattuModel>();
                
                for (int i = 0; i < count; i++) {
                    final VattuModel value = values.get(i);
                    String nameNoSign = Utils.convertSignToNoSign(value.getTenVattu()); 
                    if(nameNoSign.contains(filterText)) 
					{
                    	newValues.add(value);							
					}
                }

                results.values = newValues;
                results.count = newValues.size();
            }

            return results;
        }

        @SuppressWarnings("unchecked")
		@Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
        	currentFilter = constraint;
            vattuListShowing = (List<VattuModel>) results.values;
            if (results.count > 0) {
                DanhMucVatTuAdapter.super.notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }

}
